﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Fis.Win.Utils;

namespace Fis.Win.Forms
{
    public partial class AidsListForm : ListForm
    {
        Dictionary<DevExpress.XtraTab.XtraTabPage, DevExpress.XtraGrid.GridControl> registry
            = new Dictionary<DevExpress.XtraTab.XtraTabPage, DevExpress.XtraGrid.GridControl>();

        public AidsListForm()
        {
            InitializeComponent();
            RightsName = "BD.AIDS";

        }

        public override void InitializeViewUI()
        {
            var key = ViewModel["key"];

            var group = UIUtils.ViewConfig.Tables["aidsgroup"];

            foreach (var i in group.AsEnumerable())
            {
                var page = xtraTabControl1.TabPages.Add(i["caption"].ToString());

                var gc = UIUtils.CreateGridControl();
                CreateColumns(gc.MainView as DevExpress.XtraGrid.Views.Grid.GridView, i["key"].ToString());
                page.Controls.Add(gc);

                page.Tag = i["key"];
                registry[page] = gc;

                //显示所有类别 
                if (ViewModel.ContainsKey("showAll"))
                {
                    page.PageVisible = true;
                }
                else
                {
                    //显示指定类别
                    page.PageVisible = false;
                    if (page.Tag.Equals(key))
                    {
                        xtraTabControl1.SelectedTabPage = page;
                        page.PageVisible = true;
                    }
                }
            }


        }

        public override void InitializeBinding()
        {
            var d = ViewModel["viewData"] as DataTable;
            foreach (var entry in registry.AsEnumerable())
            {
                var s = d.Select(string.Format("FGROUP='{0}'", entry.Key.Tag));
                if (s.Length > 0)
                    entry.Value.DataSource = s.CopyToDataTable();
                else
                {
                    entry.Value.DataSource = null;
                }
            }
        }

        private void CreateColumns(DevExpress.XtraGrid.Views.Grid.GridView view, string group)
        {
            //默认添加 编码，名称
            UIUtils.CreateColumn(view, "编码", "FCODE", 0);
            UIUtils.CreateColumn(view, "名称", "FNAME", 1);
            var colGroup = UIUtils.CreateColumn(view, "类别", "FGROUP", 2);
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit edGroup
                = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            colGroup.ColumnEdit = edGroup;
            UIUtils.LookUpBinding(edGroup, UIUtils.ViewConfig.Tables["aidsgroup"], "caption", "key");

            var colDefault = UIUtils.CreateColumn(view, "默认", "FDEFAULT", 3);
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit edDefault
                 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            colDefault.ColumnEdit = edDefault;
            UIUtils.LookUpBinding(edDefault, CacheContext.YesNoCache(), "display", "value");

            var d = UIUtils.ViewConfig.Tables["aidscolumn"];

            foreach (var i in d.Select(string.Format("group='{0}'", group)))
            {
                UIUtils.CreateColumn(view
                    , i["caption"].ToString()
                    , i["field"].ToString()
                    , Convert.ToInt32(i["index"].ToString())
                    );
            }
        }

        protected override void NewProcess()
        {
            var page = xtraTabControl1.SelectedTabPage;

            if (page == null) return;

            System.Collections.Hashtable m = new System.Collections.Hashtable();
            m["FGROUP"] = page.Tag;

            UIManager.ShowEdit<AidsEditForm>("AidsEditViewProvider", Agile.Engine.View.ViewState.AddNew, m);
            CacheContext.RefreshCache(ViewProvider.DataTableName);
            RefreshProcess();
        }

        protected override void EditProcess()
        {
            var page = xtraTabControl1.SelectedTabPage;

            if (page == null) return;
            var view = registry[page].DefaultView as DevExpress.XtraGrid.Views.Grid.GridView;
            var d = view.GetFocusedDataRow();
            if (d == null) return;
            var m = Agile.Engine.Utils.DataUtils.ToEditModel("viewData", d);
            m["FGROUP"] = page.Tag;
            UIManager.ShowEdit<AidsEditForm>("AidsEditViewProvider", Agile.Engine.View.ViewState.Modify, m);
            CacheContext.RefreshCache(ViewProvider.DataTableName);
            RefreshProcess();
        }

        protected override void DelProcess()
        {
            var gridView1 = registry[xtraTabControl1.SelectedTabPage].DefaultView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (gridView1 == null || gridView1.FocusedRowHandle < 0)
                return;
            var data = gridView1.GetDataRow(gridView1.FocusedRowHandle);

            if (DialogResult.Yes == DevExpress.XtraEditors.XtraMessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.YesNo))
            {
                ViewModel["SID"] = data["SID"];
                var exec = ViewProvider.ExecuteUpdate(ViewModel);
                if (exec)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("删除成功");
                    CacheContext.RefreshCache(ViewProvider.DataTableName);
                    RefreshProcess();
                }
                else
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("删除失败:" + Message);
                }
            }
        }

        protected override void FindProcess(string value)
        {
            var gridView1 = registry[xtraTabControl1.SelectedTabPage].DefaultView as DevExpress.XtraGrid.Views.Grid.GridView;
            gridView1.ApplyFindFilter(value);
        }

        protected override void ExportProcess(string file)
        {
            var option = new DevExpress.XtraPrinting.XlsExportOptions();
            option.SheetName = Text;

            registry[xtraTabControl1.SelectedTabPage].ExportToXls(file, option);
        }

        public override string FromXls(string path)
        {
            var error = string.Empty;
            var data = DataTransUtils.ReadSheet(path, Text, ref error);

            //读取出错
            if (data == null)
            {
                return "Excel格式错误或者Excel中的Sheet名称不正确。";
            }

            ///实体数据
            DataTable source = (ViewModel["viewData"] as DataTable);
            DataTable schema = source.Copy();
            schema.Clear();
            DataTable group = UIUtils.ViewConfig.Tables["aidsgroup"];
            ///行循环
            foreach (DataRow row in data.AsEnumerable())
            {
                //新行
                var newRow = schema.NewRow();

                newRow["FCODE"] = row["编码"];
                newRow["FNAME"] = row["名称"];

                if (Agile.Engine.Utils.StringUtils.IsEmpty(row["类别"]))
                {
                    return string.Format("导入失败，原因：类别[{0}]不能为空", row["类别"]);
                }

                //类别转换
                var trans = group.Select(string.Format("caption='{0}'", row["类别"].ToString().Trim()));

                if (trans.Length == 0)
                {
                    return string.Format("导入失败，原因：类别[{0}]不存在", row["类别"]);
                }

                var groupId = trans[0]["key"].ToString();
                newRow["FGROUP"] = groupId;
                newRow["FDEFAULT"] = false;
                //编码不能重复
                var validCode = schema.Compute("Count(FCODE)", string.Format("FCODE='{0}' AND FGROUP='{1}'", newRow["FCODE"], groupId));
                if (ReportUtils.NullParse(validCode) > 0)
                {
                    return string.Format("导入失败，原因：类别[0]编码[{1}]重复", row["类别"], newRow["FCODE"]);
                }

                schema.Rows.Add(newRow);
            }

            ViewModel["viewData"] = schema;
            InitializeBinding();

            return string.Empty;
        }
    }
}
